package cn.edu.nju.askinginhand.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import cn.edu.nju.askinginhand.util.JSONParser;

public class RegisterActivity extends Activity {

	EditText usernameEdit;
	EditText nameEdit;
	EditText passEdit;
	EditText confirmPassEdit;
	Button confirmBtn;
	Button cancelBtn;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.register);
		
		usernameEdit = (EditText)findViewById(R.id.usernameEdit);
		nameEdit = (EditText)findViewById(R.id.nameEdit);
		passEdit = (EditText)findViewById(R.id.passEdit);
		confirmPassEdit = (EditText)findViewById(R.id.confirmPassEdit);
		confirmBtn = (Button)findViewById(R.id.confirmBtn);
		cancelBtn = (Button)findViewById(R.id.cancelBtn);
		
		initConfirmBtn();
		initCancelBtn();
	}
	
	private void initConfirmBtn() {
		confirmBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				/**
				 * TODO : check valid
				 */
				String username = usernameEdit.getText().toString();
				String name = nameEdit.getText().toString();
				String pass = passEdit.getText().toString();
				String confirmPass = confirmPassEdit.getText().toString();

				if(!pass.equals(confirmPass)) {
					Toast.makeText(RegisterActivity.this,"重复密码不一致",Toast.LENGTH_LONG).show();
					return;
				}
				
				String msg = getRegisterMsg(username,name,pass);
				
				if(msg.equals("fail")) {
					Toast.makeText(RegisterActivity.this,"请尝试其他用户名",Toast.LENGTH_LONG).show();
					return;
				}
				if(msg.equals("success")) {
					Toast.makeText(RegisterActivity.this,"注册成功",Toast.LENGTH_LONG).show();
					RegisterActivity.this.finish();
				}
			}
		});
	}
   
	public String getRegisterMsg(String username,String name,String password) {
		List <NameValuePair> params = new ArrayList <NameValuePair>();
		params.add(new BasicNameValuePair("name", name));
		params.add(new BasicNameValuePair("username", username));
		params.add(new BasicNameValuePair("password", password)); 
		String raw = JSONParser.getOut("UserRegisterAction"+LoginActivity.filter,params);
		//Toast.makeText(this, raw, Toast.LENGTH_SHORT).show();		
		return JSONParser.getStringData(raw);
	}
	
	private void initCancelBtn() {
		System.out.println("cancelBtn initialized");
		cancelBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				System.out.println("cancelBtn clicked");
				RegisterActivity.this.finish();
			}
		});
	}
	    
}
